import {useCommonStore} from "@/stores/commonStore";
import type {WxLoginResponse} from "@/assets/ts/Interface";
import {getRestful} from "@/assets/ts/common";

declare const wx: any;
declare const uni: any;

// 使用临时openId
const openIdCurrent = 'default_openId_currently' + new Date().getTime();

// 由用户点击时调用
async function handleUserLoginAndInfo(): Promise<void> {
    try {
        const commonStore = useCommonStore();
        const loginRes: WxLoginResponse = await new Promise((resolve, reject) => {
            wx.login({
                success: resolve,
                fail: reject
            });
        });

        if (loginRes.code) {
            console.log('登录成功，code:', loginRes.code);

            try {
                // @ts-ignore
                const result: { openId: string } = await getRestful(`/api/wechat/login/${loginRes.code}`, false);

                // @ts-ignore
                if (result && result.openId) {
                    commonStore.openId = result.openId
                } else {
                    uni.showToast({
                        title: 'openId获取失败，使用临时登录',
                        icon: 'none'
                    });
                    commonStore.openId = openIdCurrent;
                }

                // 跳转到主页面
                uni.switchTab({
                    url: '/pages/account/index',
                });

            } catch (error) {
                console.log('获取openId失败:', error);
                uni.showToast({
                    title: '获取openId失败，请重试',
                    icon: 'none'
                });
                commonStore.openId = openIdCurrent;
            }

        } else {
            commonStore.openId = openIdCurrent;
            uni.showToast({
                title: '获取Code失败，使用临时登录',
                icon: 'none'
            });
        }

    } catch (error) {
        console.log('登录或获取用户信息时出错:', error);
        uni.showToast({
            title: '登录失败，请重试',
            icon: 'none'
        });
    }
}

export {
    handleUserLoginAndInfo
};
